#include "msgq.h"
#include "bank.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int msgid = 0;
MSG_CTOS ctos = {};
MSG_STOC stoc = {};

void take(void)
{
	char path[80] = {};
	char path0[40] = ACCOUNT_PATH;
	sprintf(path,"%s%s.dat",path0,ctos.acc.id);
	
	int fd = open(path,O_RDWR);
	int ret = read(fd,&stoc.acc,sizeof(Account));
	close(fd);
	if(ret != 0)
	{
		stoc.acc.balance -= ctos.acc.balance;
		if(0 > stoc.acc.balance)
		{
			strcpy(stoc.info,"needmore");
			return;
		}
		int fd2 = open(path,O_RDWR);
		int ret1 = write(fd2,&stoc.acc,sizeof(Account));
		close(fd2);
		if(0 == ret1)
		{
			strcpy(stoc.info,"write");
			puts(stoc.info);
		}
		else 
		{
			int fd3 = open(path,O_RDWR);
			int ret2 = read(fd3,&stoc.acc,sizeof(Account));
			close(fd3);
			if(0 == ret2)
			{
				strcpy(stoc.info,"read2");
				puts(stoc.info);
			}
			else
			{
				strcpy(stoc.info,"success");
			}
		}
	}
	else
	{
		strcpy(stoc.info,"read1");
		puts(stoc.info);	//服务器出错输出错误位置
	}
}

int main(int argc,const char* argv[])
{
	printf("argv %s\n",argv[0]);
	msgid = get_msg(ACCOUNT_PATH,SUBP_CNT);
	
	for(;;)
	{
		recv_msg(msgid,&ctos,sizeof(MSG_CTOS),MSGTY_TAKE);
		take();
		stoc.type = ctos.return_type;
		send_msg(msgid,&stoc,sizeof(MSG_STOC));
	}	
}
